import React, { PureComponent } from 'react'
import { history } from '@umijs/max'
import { message, Select } from 'antd'
import {
  BreadcrumbBar, Logger, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import { offlineLog, offlineStop } from './api'
import { getHashParameterByName } from '@/utils/helper'
import Tools from '@/utils/Tools'
import styles from './index.less'

const Bus = Tools.Bus

const { OperateItem } = ProTableOperate
const { Option } = Select

const status = [
  {
    key: 1,
    value: '待发布',
  },
  {
    key: 2,
    value: '已发布',
  },
  {
    key: 3,
    value: '未运行',
  },
  {
    key: 4,
    value: '运行中',
  },
  {
    key: 5,
    value: '成功',
  },
  {
    key: 6,
    value: '失败',
  },
  {
    key: 7,
    value: '停止',
  },
]

const statusObj = {
  1: {
    key: 1,
    value: '待发布',
    icon: 'icon-daiban',
    color: '#0084FF',
  },
  2: {
    key: 2,
    value: '已发布',
    icon: 'icon-yifabu',
    color: '#43A047',
  },
  3: {
    key: 3,
    value: '未运行',
    icon: 'icon-weiyunhang',
    color: '#0084FF',
  },
  4: {
    key: 4,
    value: '运行中',
    icon: 'icon-yunhangzhong_1',
    color: '#0084FF',
  },
  5: {
    key: 5,
    value: '成功',
    icon: 'icon-chenggong',
    color: '#43A047',
  },
  6: {
    key: 6,
    value: '失败',
    icon: 'icon-shibai1',
    color: '#EF5350',
  },
  7: {
    key: 7,
    value: '停止',
    icon: 'icon-weiyunhang',
    color: '#0084FF',
  },
}

export default class OfflineHistory extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      query: {
        taskId: getHashParameterByName('id'),
      },
      executeType: '',
      taskStatus: '',
      loggerList: [],
      menus: [{ name: '离线同步' }, { name: '历史任务' }],
      columns: [
        {
          title: '任务名称', width: '15%', dataIndex: 'taskName', key: 'taskName',
        },
        {
          title: '任务状态',
          width: '10%',
          dataIndex: 'taskStatus',
          key: 'taskStatus',
          render: (text, record) => <span> <i style={{ color: statusObj[text].color }} className={`iconfont ${statusObj[text].icon}`} /> {statusObj[text].value}</span>,
        },
        {
          title: '任务类型',
          width: '10%',
          dataIndex: 'executeType',
          key: 'executeType',
          render: (text, record) => <span>{['周期任务', '手动任务'][text]}</span>,
        },
        {
          title: '开始时间', width: '15%', dataIndex: 'startTime', key: 'startTime',
        },
        {
          title: '结束时间', width: '15%', dataIndex: 'endTime', key: 'endTime',
        },
        {
          title: '执行时长（秒）', width: '10%', dataIndex: 'duration', key: 'duration',
        },
        {
          title: '责任人', width: '10%', dataIndex: 'creator', key: 'creator',
        },
        {
          title: '操作',
          // dataIndex: 'action',
          // key: 'action',
          width: '15%',
          render: (text, record) => (
            <ProTableOptions>
              <span onClick={() => {
                this.setState({
                  loggerList: [],
                })
                this.offlineLog(record.id, 0)
                Bus.emit('iconUpFn2')
              }}
              >查看日志
              </span>
              {record.taskStatus == 4 ? (
                <span onClick={() => {
                  this.offlineStop(record.id)
                }}
                >停止
                </span>
              ) : null}
            </ProTableOptions>
          ),
        },
      ],
      loading: false,
    }
    this.tableRef = React.createRef()
    this.logger = React.createRef()
  }

  componentDidMount() {
  }

  componentWillUnmount() {
    this.time && clearTimeout(this.time)
  }

  offlineLog = (logId, offset) => {
    offlineLog({ logId, offset }).then((res) => {
      clearTimeout(this.time)
      if (res.status === 200) {
        if (res.data) {
          if (res.data.logEnd) {
            const { query, executeType, taskStatus } = this.state
            this.setState({
              query: {
                ...query,
                executeType: executeType || '',
                taskStatus: taskStatus || '',
              },
            })
            clearTimeout(this.time)
          } else {
            this.time = setTimeout(() => {
              this.offlineLog(logId, res.data.offset)
            }, 3000)
          }
          let { loggerList } = this.state
          if (res.data.logContent && res.data.logContent.length) {
            loggerList = loggerList.concat(res.data.logContent)
          }
          this.setState({
            loggerList,
          })
        }
      } else {
        clearTimeout(this.time)
      }
    })
  }

  offlineStop = (logId) => {
    this.setState({ loading: true })
    offlineStop({ logId }).then((res) => {
      setTimeout(() => {
        this.setState({
          loading: false,
        })
        const { query, executeType, taskStatus } = this.state
        if (res.status === 200) {
          message.success(res.msg)
          this.setState({
            query: {
              ...query,
              executeType: executeType || '',
              taskStatus: taskStatus || '',
            },
          })
        } else {
          message.error(res.msg)
        }
      }, 2000)
    })
  }

  render() {
    const {
      query, executeType, taskStatus, menus, loggerList, loading,
    } = this.state
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i className="iconfont icon-zuo" />
          <span onClick={() => { history.push('/dataIntegrate/offline') }}>历史任务</span>
        </div>
        <div className={styles.page_content_column}>
          <div className={`${styles.page_content_right} ${styles.page_content_right_flex}`}>
            <ProTableOperate style={{ marginBottom: 12 }}>
              <OperateItem>
                <span>任务状态</span>
                <Select
                  allowClear
                  placeholder="请选择任务状态"
                  onChange={(value) => {
                    this.tableRef?.current?.resetPageNum()
                    this.setState({
                      taskStatus: value,
                      loggerList: [],
                    }, () => {
                      this.logger.current.iconDownFn()
                      this.setState({
                        query: {
                          ...query,
                          executeType: executeType || '',
                          taskStatus: value || '',
                        },
                      })
                    })
                  }}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  {status.map((item) => <Option value={item.key} key={item.key}>{item.value}</Option>)}
                </Select>
              </OperateItem>
              <OperateItem>
                <span>任务类型</span>
                <Select
                  allowClear
                  placeholder="请选择任务类型"
                  onChange={(value) => {
                    this.tableRef?.current?.resetPageNum()
                    this.setState({
                      executeType: value,
                      loggerList: [],
                    }, () => {
                      this.logger.current.iconDownFn()
                      this.setState({
                        query: {
                          ...query,
                          executeType: value || value === 0 ? value : '',
                          taskStatus: taskStatus || '',
                        },
                      })
                    })
                  }}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  <Option value={0} key={0}>周期任务</Option>
                  <Option value={1} key={1}>手动任务</Option>
                </Select>
              </OperateItem>
            </ProTableOperate>
            <ProTable
              loading={loading}
              rowKey="key"
              columns={this.state.columns}
              ref={this.tableRef}
              query={query}
              border={false}
              url="/api/v1/integration/offline/task/history"
            />
          </div>
          <Logger
            list={loggerList || []}
            // hide={hide}
            ref={this.logger}
          />
        </div>
      </div>
    )
  }
}
